/*
 * @Author: fjxcjm 3157329468@qq.com
 * @Date: 2024-10-08 18:08:58
 * @LastEditors: fjxcjm 3157329468@qq.com
 * @LastEditTime: 2024-10-16 11:00:28
 * @FilePath: \vue3-project\src\router\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createRouter, createWebHashHistory } from "vue-router";
import route from "./modules"; // 导入路由模块
import { isLoggedIn } from "../utils/token"; // 导入检查 token 的函数
import { setRoutesByRole } from "@/utils/permission";

const router = createRouter({
  history: createWebHashHistory(),
  routes: route,
});

router.beforeEach(async (to, from, next) => {
  const userRole = localStorage.getItem("userRole");
  if (userRole) await setRoutesByRole(userRole);
  const loggedIn = isLoggedIn();

  // 如果用户已登录，直接继续访问
  if (loggedIn) {
    next();
  }

  // 如果用户未登录，且访问的不是登录页，重定向到登录页
  if (to.path !== "/login") {
    return next("/login");
  }

  // 放行
  next();
});

export default router;
